<template>
	<view :style="[{paddingTop:(CustomBar+10)+'px'},{paddingBottom:'50px'}]">
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="backText"></block>
			<block slot="content">确认订单</block>
		</cu-custom>
		<view class="address" @click="goTruthAdd" v-if="fromType!='offline'">
			<view class="" v-if="!noAddress">
				<view class="">
					<view class="text-cut ">
						{{nowAddress.name}}
					</view>
					<view class="">
						{{nowAddress.phone}}
					</view>
				</view>
				<view class="">
					<tui-icon :name="'gps'" :size="'15'" :color="'#333'"></tui-icon>
					<view class="add-text">
						{{nowAddress.all_address_str}}{{nowAddress.address}}
					</view>
				</view>
			</view>
			<view class="no-address" v-if="noAddress">
				点击添加地址~
			</view>
			<tui-icon :name="'arrowright'" :size="'30'" :color="'#999'"></tui-icon>
		</view>
		<view class="goods">
			<view class="tit">
				<tui-icon :name="'shop'" :size="'25'" :color="'#333'"></tui-icon>
				<view class="">{{showData.shopInfo.shopName}}</view>
			</view>
			<view class="goods-item" v-for="(item,index) in showData.productList" :key="index">
				<image :src="item.goodsImg" mode=""></image>
				<view class="info">
					<view class="">{{item.goodsName}}</view>
					<view class="">
						<view class="">
							<text v-if="item.shopPrice!=''" class="text-price text-colorP">{{item.shopPrice}}</text>
							<text v-if="item.shopPrice!='' && item.integral!=''" class="text-colorP">+</text>
							<text v-if="item.integral!=''" class="text-colorP">{{item.integral}}</text>
							<text v-if="item.integral!=''" class="text-colorP  j_f">积分</text>
						</view>
						<view class="">
							x{{item.saleNums}}
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="order-info">
			<view class="order-item" v-if="zoomScord>0">
				<view class="left">
					需消耗积分
				</view>
				<view>
					<text :style="isPrero?'text-decoration: line-through;':''">{{zoomScord}}</text>
					<text v-if="isPrero">{{isPrero?'(特权抵扣)':''}}</text>
				</view>
			</view>
			<view class="order-item" @click='Polish' v-if="showNeedPolish">
				<view class="left">
					是否补齐?
				</view>
				<view class="">
					<view class="truth" :class="isPolishing?'active':''"></view>
				</view>
			</view>
			<view class="order-item" @click='Prero' v-if="hasPrero && fromType!='offline'">
				<view class="left">
					是否使用特权卡，享受免积分
				</view>
				<view class="">
					<view class="truth" :class="isPrero?'active':''"></view>
				</view>
			</view>
			<view class="order-item">
				<view class="left">
					运费
				</view>
				<view class="">
					免运费
				</view>
			</view>
			<view class="order-item" v-if="showData.shopInfo.shopId!=3">
				<view class="left">
					税费
				</view>
				<view class="">
					免税
				</view>
			</view>
			<view class="order-item beizhu">
				<view class="left">
					备注
				</view>
				<view class="">
					<textarea v-model="remark" placeholder="还有什么需要备注的吗？" />
					</view>
			 </view>
		</view>
		<view class="bottom-user">
			<view class="">
				<text>共{{zoomProLength}}件</text>
				<text>，应付</text>
				<text class="text-price text-colorP" style="margin-left: 10rpx;">{{zoomPrice}}</text>
				<!-- <text v-if="zoomPrice!=0 && zoomScord!=0" class="text-colorP">+</text>
				<text v-if="zoomScord!=''" class="text-colorP">{{zoomScord}}</text>
				<text v-if="zoomScord!=''" class="text-colorP  j_f">积分</text> -->
			</view>
			<view class="bg-colorP" @click="fromType!='offline'?goChance():offlinePay()">
				提交订单
			</view>
		</view>
	</view>
</template>

<script>
	import tuiIcon from "@/components/thorUI/icon.vue";
	export default {
		components: {
			tuiIcon
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				noAddress: false,
				nowAddress:{},
				truthAddId:'',
				
				showData:{},
				zoomPrice:0,
				zoomScord:0,
				zoomProLength:'',
				hasScord: 0,
				// 是否补齐
				isPolishing: false,
				remark: '',
				showNeedPolish: false,
				hasPrero: false,
				preroId: '',
				isPrero: false,
				
				
				fromType:'',
				
				// 押金
				isCash: 0
			}
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: '#ffffff'
			})
		},
		onShow() {
			// 是否有选择的地址
			if(uni.getStorageSync('truthAddId')){
				this.truthAddId = uni.getStorageSync('truthAddId')
				uni.removeStorageSync('truthAddId')
			}
			this.getAddress()
		},
		onLoad(options) {
			if(options.from){
				this.fromType = options.from?options.from:''
			}
			if(options.isCash){
				this.isCash = options.isCash
			}
			this.getUser()
			// #ifdef H5
			this.wxConfig()
			// #endif
		},
		
		methods:{
			/**配置jsApi**/
			wxConfig() {
				var that = this
				let system = uni.getSystemInfoSync(); // 获取系统信息
				var url = ''
				if (system.platform === 'android') { // 判断平台
					url = window.location.href
				} else {
					url = encodeURIComponent(window.location.href.split('#')[0])
				}
				this.$request({
					url: '/JsTicket/getSignPackage',
					data: {
						'url': url,
					},
					success: res => {
						var result = res.data.data
						that.$wx.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端console.log出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: result.appId, // 必填，公众号的唯一标识
							timestamp: result.timestamp, // 必填，生成签名的时间戳
							nonceStr: result.nonceStr, // 必填，生成签名的随机串
							signature: result.signature, // 必填，签名
							jsApiList: [
								'checkJsApi',
								'chooseWXPay',
							] // 必填，需要使用的JS接口列表
						});
						uni.hideLoading()
					},
					fail: () => {},
					complete: () => {}
				});
			},
			getUser(){
				var that = this;
				this.$request({
					url: '/User/get_user_info',
					success: res => {
						if (res.data.status == 1) {
							uni.hideLoading()
							// 获取商品
							if(uni.getStorageSync('needData')){
								that.showData = uni.getStorageSync('needData')
								that.hasScord = res.data.data.jifen
								that.preroId = res.data.data.prerogative_id
								if(res.data.data.prerogative_id!=0 && that.fromType!='offline'){
									that.hasPrero = true
								}
								that.computedPrice()
							}
							
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			Polish(){
				this.isPolishing = !this.isPolishing
				// 补齐订单
				if(this.isPolishing){
					if(this.isPrero){
						this.isPrero = false
					}
					this.zoomPrice += (this.zoomScord-this.hasScord)
				}else{
					this.zoomPrice -= (this.zoomScord-this.hasScord)
				}
			},
			
			// 是否使用特权卡
			Prero(){
				this.isPrero = !this.isPrero
				if(this.isPrero){
					this.computedPrice(1)
				}else{
					this.computedPrice(2)
				}
			},
			
			// 处理浮点数
			mul(num1, num2) {
				var m = 0,
					r1, r2;
				var s1 = num1.toString();
				var s2 = num2.toString();
				try {
					m += s1.split('.')[1].length
				} catch (e) {
			
				}
				try {} catch (e) {
					m += s2.split('.')[1].length
				}
				r1 = Number(num1.toString().replace(".", ""));
				r2 = Number(num2.toString().replace(".", ""));
				return r1 * r2 / Math.pow(10, m);
			},
			add(num1, num2) {
				var r1, r2, m;
				try {
					r1 = num1.toString().split('.')[1].length;
				} catch (e) {
					r1 = 0
				}
				try {
					r2 = num2.toString().split('.')[1].length;
				} catch (e) {
					r2 = 0
				}
				m = Math.pow(10, Math.max(r1, r2));
				return Math.round(num1 * m + num2 * m) / m;
			},
			computedPrice(status){
				var that = this
				var product = this.showData.productList
				var zoomPrice = 0
				var zoomScord = 0
				var zoomProLength = 0
				product.forEach(item=>{
					if(status==1){
						zoomPrice = that.add(zoomPrice, that.mul(item.prerogative, item.saleNums))
					}else{
						zoomPrice = that.add(zoomPrice, that.mul(item.shopPrice, item.saleNums))
					}
					zoomScord = that.add(zoomScord, that.mul(item.integral, item.saleNums))
					zoomProLength += item.saleNums
				})
				that.zoomPrice = zoomPrice
				that.zoomScord = zoomScord
				that.zoomProLength = zoomProLength
				if(that.isPrero){
					this.isPolishing = false
				}else{
					// 检测到需要补齐
					if(that.hasScord<zoomScord){
						uni.showModal({
							content:'系统检测到您的购物积分不足，是否使用现金补齐剩余积分？',
							confirmText:'立即补齐',
							success(res){
								if(res.confirm){
									that.isPolishing = false
									that.Polish()
								}
							},
						})
						that.showNeedPolish = true
					}	
				}
				
			},
			goTruthAdd(){
				uni.navigateTo({
					url:'/pages/addressAdmain?status=1'
				})
			},
			// 线下提交
			offlinePay(){
				var that = this
				 // 积分需要补齐的
				 if(this.zoomScord && this.hasScord<this.zoomScord && !this.isPolishing && !this.isPrero){
				 	uni.showModal({
				 		content:'您的购物积分不足，是否使用现金补齐完成支付？',
				 		confirmText:'立即补齐',
				 		cancelText:'再看看',
				 		success(res){
				 			if(res.confirm){
				 				that.isPolishing = false
				 				that.Polish()
				 			}
				 		},
				 	})
				 	return false
				 }
				 // 是否需要补齐积分  补了多少钱
				 var extraMoney = 0
				 if(this.zoomScord && this.isPolishing){
				 	extraMoney = (this.zoomScord-this.hasScord)
				 }
				 // 替换saleNums字段为number字段
				 var requestPro = []
				 var zoomNums = 0
				 var productList = that.showData.productList
				 productList.forEach(item=>{
				 	var thisItem = {}
				 	thisItem['saleNum'] = item.saleNums
				 	thisItem['id'] = item.id
				 	thisItem['price'] = item.shopPrice
				 	thisItem['integral'] = item.integral
				 	thisItem['product_name'] = item.goodsName
				 	thisItem['image'] = item.goodsImg
					zoomNums += item.saleNums
				 	requestPro.push(thisItem)
				 })
				 this.$request({
				 	url: '/OnlineOrder/order_pay',
					method :'POST',
				 	data:{
						total_num:zoomNums,
				 		business_id: that.showData.shopInfo.shopId,
				 		pay_price: that.zoomPrice,
				 		// pay_price:'0.01',
				 		product_info: JSON.stringify(requestPro),
				 		// 非必填
				 		use_integral: extraMoney==0?that.zoomScord:that.hasScord,
				 		extraMoney:extraMoney,
						is_cash: that.isCash
				 	},
				 	success: res => {
				 		if (res.data.status == 1) {
				 			var param = res.data.data
							if(that.zoomPrice==0){
								// 直接成单
								uni.showModal({
									content: '购买成功',
									showCancel:false,
									success: function (res) {
										if (res.confirm) {
											uni.redirectTo({
												url: `/pages/orderDetail?id=${param.order_id}&status=needSave`,
												success(res){
													uni.removeStorageSync('needData')
												}
											}) 
										} else if (res.cancel) {
											
										}
									}
								});
							}else{
								that.wxPay(param)
							}
				 		}
				 	},
				 	fail: () => {},
				 	complete: () => {}
				 });
			},
			// 支付
			wxPay(param){
				var that = this
				// #ifdef H5
				that.$wx.checkJsApi({
					jsApiList: [
						'chooseWXPay'
					],
					success: function(res) {
						that.$wx.chooseWXPay({
							appId: param.appId,
							timestamp: param.timeStamp,
							nonceStr: param.nonceStr,
							package: param.package,
							signType: param.signType,
							paySign: param.paySign,
							success: function(log) {
								if (log.errMsg == 'chooseWXPay:ok') {
									uni.showToast({
										title:'支付成功'
									})
									setTimeout(function(){
									   if(that.fromType!='offline'){
										   uni.redirectTo({
											url: '/pages/cloudMall/logisticsOrderDetail?orderId='+param.order_id,
												success(res){
													uni.removeStorageSync('needData')
												}
										   });
									   }else{
										  uni.redirectTo({
											url: `/pages/orderDetail?id=${param.order_id}&status=needSave`,
											success(res){
												uni.removeStorageSync('needData')
											}
										  }) 
									   }
									},1000)
								}
							},
							fail(err) {
								if(that.fromType!='offline'){
								   uni.redirectTo({
									url: '/pages/cloudMall/logisticsOrderDetail?orderId='+param.order_id,
										success(res){
											uni.removeStorageSync('needData')
										}
								   });
								}else{
								  uni.showToast({
									title:'支付失败'
								  })
								}
							}
						})
				
						if (res.checkResult.chooseWXPay == false) {
							alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！')
						}
					}
				})
				// #endif
				
				// #ifdef MP-WEIXIN
				// fromType==offline  线下商品  其他为商城
				wx.requestPayment({
				  'timeStamp': param.timeStamp,
				  'nonceStr': param.nonceStr,
				  'package': param.package,
				  'signType': param.signType,
				  'paySign': param.paySign,
				  success: function success(res) {
				   uni.showToast({
				   	title:'支付成功'
				   })
				   setTimeout(function(){
					   if(that.fromType!='offline'){
						   uni.redirectTo({
							url: '/pages/cloudMall/logisticsOrderDetail?orderId='+param.order_id,
								success(res){
									uni.removeStorageSync('needData')
								}
						   });
					   }else{
						  uni.redirectTo({
							url: `/pages/orderDetail?id=${param.order_id}`,
							success(res){
								uni.removeStorageSync('needData')
							}
						  }) 
					   }
				   },1000)
				  },
				  fail: function success(err) {
					  if(that.fromType!='offline'){
						   uni.redirectTo({
						   	url: '/pages/cloudMall/logisticsOrderDetail?orderId='+param.order_id,
								success(res){
									uni.removeStorageSync('needData')
								}
						   });
					  }else{
						  uni.showToast({
						  	title:'支付失败'
						  })
					  }
					  
				  }
				});
				// #endif
				
				// #ifdef !H5 && !MP-WEIXIN
				uni.showToast({
					title:'敬请期待~',
					icon:'none'
				})
				// #endif
				uni.hideLoading()
			},
			// 云商城提交
			goChance(){
				var that = this 
				if(this.noAddress){
					uni.showToast({
						title:'请先添加收货地址',
						icon:'none'
					})
					return  false
				}
				// 积分需要补齐的
				if(this.zoomScord && this.hasScord<this.zoomScord && !this.isPolishing && !this.isPrero){
					uni.showModal({
						content:'您的购物积分不足，是否使用现金补齐完成支付？',
						confirmText:'立即补齐',
						cancelText:'再看看',
						success(res){
							if(res.confirm){
								that.isPolishing = false
								that.Polish()
							}
						},
					})
					return false
				}
				// 是否需要补齐积分  补了多少钱
				var extraMoney = 0
				if(this.zoomScord && this.isPolishing){
					extraMoney = (this.zoomScord-this.hasScord)
				}
				// 替换saleNums字段为number字段
				var requestPro = []
				var productList = that.showData.productList
				productList.forEach(item=>{
					var thisItem = {}
					thisItem['number'] = item.saleNums
					thisItem['id'] = item.id
					thisItem['shopPrice'] = item.shopPrice
					requestPro.push(thisItem)
				})
				// #ifdef APP-PLUS
				uni.showToast({
					title:'敬请期待~',
					icon:'none'
				})
				// uni.navigateTo({
				// 	url:'/pages/paychance'
				// })
				return 
				// #endif
				this.$request({
					url: '/ShopOrders/order_pay',
					data:{
						shopId: that.showData.shopInfo.shopId,
						goodsMoney: that.zoomPrice,
						totalMoney:that.zoomPrice,
						// totalMoney:'0.01',
						extraJson: JSON.stringify(requestPro),
						user_address_id: that.nowAddress.id,
						// 非必填
						orderScore: 0,
						orderRemarks: that.remark,
						scoreMoney: that.zoomScord,
						useScore: that.zoomScord,
						extraMoney:extraMoney,
						is_prerogative: that.isPrero?that.preroId:0
					},
					success: res => {
						if (res.data.status == 1) {
							var param = res.data.data
							if(that.zoomPrice==0){
								// 直接成单
								uni.showToast({
									title:'购买成功'
								})
								setTimeout(function(){
									uni.redirectTo({
										url: '/pages/cloudMall/logisticsOrderDetail?orderId='+param.order_id,
										success(res){
											uni.removeStorageSync('needData')
										}
									});
								},1000)
							}else{
								that.wxPay(param)
							}
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			// 获取地址
			getAddress() {
				var that = this;
				that.tNoCont = false;
				this.$request({
					url: '/UserRelation/get_list',
					success: res => {
						if (res.data.status == 1) {
							var result = res.data.data
							if (result.length == 0) {
								that.noAddress = true
								return 
							}else{
								that.noAddress = false
							}
							var filterItem = result.filter(item => item.is_default ==1)
							if(filterItem.length>0 && !that.truthAddId){
								that.nowAddress = filterItem[0]
							}else if(that.truthAddId){
								that.nowAddress = result.filter(item => item.id == that.truthAddId)[0]
							}else{
								that.nowAddress = result[0]
							}
							that.$forceUpdate()
							uni.hideLoading()
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
		}
	}
</script>

<style>
	.address>view:nth-child(1)>view .tui-icon {
		margin-right: 10rpx;
	}

	.goods .tit .tui-icon {
		margin-right: 10rpx;
	}
</style>
<style scoped>
	page {
		background: #f5f5f5;
	}

	.address {
		width: 100%;
		padding: 20rpx 24rpx;
		background: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.address>view:nth-child(1) {
		display: flex;
		flex-direction: column;
	}

	.address>view:nth-child(1)>view {
		display: flex;
		font-size: 28rpx;
		color: #666;
		line-height: 45rpx;
	}

	.address>view:nth-child(1)>view:nth-child(1) {
		margin-bottom: 20rpx;
		display: flex;
		color: #333333;
		font-size: 30rpx;
	}

	.address>view:nth-child(1)>view:nth-child(1)>view:nth-child(1) {
		margin-right: 20rpx;
		font-weight: 500;
		max-width: 400rpx;
	}

	.address .add-text {
		max-width: 600rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.goods {
		width: 100%;
		background: #fff;
		display: flex;
		flex-direction: column;
		padding: 0 24rpx 30rpx; 
		margin-bottom: 20rpx;
	}

	.goods .tit {
		width: 100%;
		padding: 23rpx 0;
		display: flex;
		align-items: center;
	}

	.goods .tit>view {
		color: #333333;
		font-size: 28rpx;
		letter-spacing: 1rpx;
	}

	.goods-item {
		width: 100%;
		display: flex;
		box-sizing: border-box;
		margin-bottom: 20rpx;
	}

	.goods-item image {
		display: block;
		width: 200rpx;
		height: 188rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.goods-item .info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

	}

	.goods-item .info>view:nth-child(1) {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		font-size: 30rpx;
		color: #333333;
		letter-spacing: 1rpx;
		font-weight: 500;
	}
	
	.goods-item .info>view:nth-child(2) {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.goods-item .info>view:nth-child(2)>view{
		color: #333333;
		font-size: 26rpx;
		letter-spacing: 1rpx;
	}
	
	.goods-item .info>view:nth-child(2)>view:nth-child(2){
		font-weight: 300;
	}
	
	.order-info{
		width: 100%;
		padding: 0 24rpx;
		display: flex;
		flex-direction: column;
		background: #fff;
	}
	
	.order-info .order-item:last-child{
		border-bottom: none;
	}
	
	.order-item{
		border-bottom: solid 1rpx #efefef;
		padding: 30rpx 0 ;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	
	.order-item>view:nth-child(1){
		color: #333333;font-size: 28rpx;
	}
	
	.order-item>view:nth-child(2){
		color: #333333;font-size: 28rpx;
	}
	
	.truth{
		width: 40rpx;
		height: 40rpx;
		border: solid 1rpx #efefef;
		background: #fff;
		border-radius: 100%;
	}
	
	.truth.active{
		background: url('https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/istruth.png') no-repeat !important;
		background-size: 100% 100% !important;
		border: none;
	}
	
	.beizhu{
		align-items: flex-start;
	}
	
	textarea{
		color: #333;
		width: 530rpx;
		font-size: 26rpx;
		padding: 10rpx;
		box-sizing: border-box;
		text-align: right;
	}
	
	.bottom-user{
		width: 100%;
		height: 98rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		background: #fff;
		z-index:9999999;
		box-shadow: 0 -3rpx 3rpx 2rpx rgba(0,0,0,.1);
	}
	
	.bottom-user>view:nth-child(1){
		flex: 1;
		height: 98rpx;
		display: flex;
		align-items: center;
		padding-left: 20rpx;
		
	}
	
	.bottom-user>view:nth-child(1) text{
		font-size: 28rpx;
	}
	
	.bottom-user>view:nth-child(1) text:nth-child(1){
		color: #666666;
	}
	
	.bottom-user>view:nth-child(2){
		width: 250rpx;
		height: 98rpx;
		line-height: 98rpx;
		text-align: center;
		
	}
</style>
